<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\BaseController;
use App\Models\Topic;
use Illuminate\Http\Request;

class ArticleController extends BaseController
{
    public function index(Request $request)
    {
        $args = [];
        $args[] = ['type', 'article'];
        if ($groupId = $request->get('group_id')) {
            $args[] = ['group_id', $groupId];
        }
        if ($groupName = $request->get('group_name')) {
            $args[] = ['qz_community_group.title', "{$groupName}"];
        }
        if ($userId = $request->get('user_id')) {
            $args[] = ['qz_topic.user_id', $userId];
        }
        if ($nickname = $request->get('nickname')) {
            $args[] = ['qz_ucenter_member.nickname', "{$nickname}"];
        }
        if ($title = $request->get('article_title')) {
            $args[] = ['qz_topic_article.title', "{$title}"];
        }
        if ($startTime = $request->get('start_time')) {
            $args[] = ['qz_topic.create_time', '>=', $startTime];
        }
        if ($endTime = $request->get('end_time')) {
            $args[] = ['qz_topic.create_time', '<=', $endTime];
        }
        if ($status = $request->get('status')) {
            $args[] = ['qz_topic.status', $status];
        }
        $topics = Topic::leftJoin('qz_ucenter_member', 'qz_topic.user_id', '=', 'qz_ucenter_member.id')
            ->leftJoin('qz_community_group', 'qz_topic.group_id', '=', 'qz_community_group.id')
            ->leftJoin('qz_topic_article', 'qz_topic.id', '=', 'qz_topic_article.topic_id')
            ->where($args)
            ->select(
                'qz_topic_article.*',
                'qz_topic.*',
                'qz_community_group.title as group_name',
                'qz_ucenter_member.nickname'
            )
            ->forPage($request->get('page', 1), $request->get('page_size', 10))
            ->get();

        return $this->success($topics->toArray());
    }

    public function update($id, Request $request)
    {
        $topic = Topic::findOrFail($id);
        if (! $topic->isArticle()) {
            return $this->fail();
        }
        \Validator::validate($request->input(), ['status' => 'required|in:-1,1']);

        $topic->update($request->only('status') + ['update_time' => time()]);

        return $this->success();
    }

    public function show($id, Request $request)
    {

    }
}
